// routes/reservations.ts
import express from 'express';
import { ReservationService } from '../../service';

const router = express.Router();

// 获取所有预约
router.get('/', async (req, res) => {
    try {
        const reservations = await ReservationService.getAllReservations();
        res.json({
            success: true,
            data: reservations,
            count: reservations.length
        });
    } catch (error) {
        console.error('获取预约列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取预约列表失败'
        });
    }
});

// 综合搜索预约
router.get('/search', async (req, res) => {
    try {
        const { customerName, reservationTypes } = req.query;

        let typesArray: number[] | undefined;
        if (reservationTypes) {
            if (typeof reservationTypes === 'string') {
                typesArray = reservationTypes.split(',').map(Number);
            } else if (Array.isArray(reservationTypes)) {
                typesArray = reservationTypes.map(item => Number(item));
            }
        }

        const criteria: { customerName?: string; reservationTypes?: number[] } = {};
        
        if (customerName && typeof customerName === 'string') {
            criteria.customerName = customerName;
        }
        
        if (typesArray && typesArray.length > 0) {
            criteria.reservationTypes = typesArray;
        }

        const reservations = await ReservationService.searchReservations(criteria);
        res.json({
            success: true,
            data: reservations,
            count: reservations.length
        });
    } catch (error) {
        console.error('搜索预约失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索预约失败'
        });
    }
});

// 新增预约
router.post('/', async (req, res) => {
    try {
        const { customerName, reservationType, reservationMessage } = req.body;

        // 验证必填字段
        if (!customerName || !reservationType || !reservationMessage) {
            return res.status(400).json({
                success: false,
                message: '客户名、预约类型和预约信息为必填项'
            });
        }

        const success = await ReservationService.addReservation(
            customerName,
            Number(reservationType),
            reservationMessage
        );

        if (success) {
            res.status(201).json({
                success: true,
                message: '预约添加成功'
            });
        } else {
            res.status(500).json({
                success: false,
                message: '预约添加失败'
            });
        }
    } catch (error: any) {
        if (error.message.includes('不存在的用户')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else if (error.message.includes('预约资源不可用')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        }else if (error.message.includes('预订记录已存在')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: error.message
            });
        }
    }
});

// 取消预约
router.delete('/cancel', async (req, res) => {
    try {
        const { reservationKey } = req.body;

        if (!reservationKey) {
            return res.status(400).json({
                success: false,
                message: '预约key为必填项'
            });
        }

        const success = await ReservationService.cancelReservation(reservationKey);

        if (success) {
            res.json({
                success: true,
                message: '预约取消成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '预约不存在或取消失败'
            });
        }
    } catch (error: any) {
        console.error('取消预约失败:', error);

        if (error.message.includes('无效的reservationKey格式') || 
            error.message.includes('不支持的预约类型')) {
            res.status(400).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: '取消预约失败'
            });
        }
    }
});

// 根据客户名获取预约
/*router.get('/customer/:customerName', async (req, res) => {
    try {
        const { customerName } = req.params;

        const reservations = await ReservationService.getReservationsByCustomer(customerName);
        res.json({
            success: true,
            data: reservations,
            count: reservations.length
        });
    } catch (error) {
        console.error('获取客户预约失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户预约失败'
        });
    }
});*/

// 根据预约类型获取预约
/*router.get('/type/:reservationType', async (req, res) => {
    try {
        const { reservationType } = req.params;
        const typeNumber = Number(reservationType);

        if (isNaN(typeNumber) || typeNumber < 1 || typeNumber > 3) {
            return res.status(400).json({
                success: false,
                message: '预约类型必须是1(航班)、2(酒店)或3(巴士)'
            });
        }

        const reservations = await ReservationService.getReservationsByType(typeNumber);
        res.json({
            success: true,
            data: reservations,
            count: reservations.length
        });
    } catch (error) {
        console.error('获取类型预约失败:', error);
        res.status(500).json({
            success: false,
            message: '获取类型预约失败'
        });
    }
});*/

// 检查预约是否存在
router.get('/exists/:reservationKey', async (req, res) => {
    try {
        const { reservationKey } = req.params;

        const exists = await ReservationService.reservationExists(reservationKey);
        res.json({
            success: true,
            exists
        });
    } catch (error) {
        console.error('检查预约存在失败:', error);
        res.status(500).json({
            success: false,
            message: '检查预约存在失败'
        });
    }
});

export default router;